package com.rim.samples.device.helloworlddemo;

import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class EchoScreen extends MainScreen
{
    private ButtonField startButton;

    private static long _tStart;

    private static RichTextField _logField = new RichTextField();

    private static boolean log = true;

    private RecvStream mRecvStream;
    private SendStream mSendStream;

    /**
     * Creates a new MyScreen object
     */
    public EchoScreen()
    {
        // Set the displayed title of the screen
        setTitle("Echo");

        startButton = new ButtonField("Start");
        startButton.setRunnable(new Runnable()
        {
            public void run()
            {
                startEcho();
            }
        });
        add(startButton);

        ButtonField logButton = new ButtonField("log");
        logButton.setRunnable(new Runnable()
        {
            public void run()
            {
                log = !log;
            }
        });
        add(logButton);

        // add log area
        _tStart = System.currentTimeMillis();
        Font f = _logField.getFont();
        _logField.setFont(f.derive(f.getStyle(), f.getHeight() * 3 / 5));
        add(_logField);
    }

    private void startEcho()
    {
        // new EchoPlayer().startEcho();

        mSendStream = new SendStream("");
        mRecvStream = new RecvStream();
        mSendStream.start();
        Thread lTmpThread = new Thread(new Runnable()
        {
            public void run()
            {
                mRecvStream.start();
            }
        });
        lTmpThread.start();
    }

    public static void log(final String sValue)
    {
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                long t = System.currentTimeMillis() - _tStart;
                if (false)
                {
                    _logField.insert("[" + ((t / 1000) + "." + t % 1000) + "] "
                        + sValue + "\n");
                }
            }
        });
    }
}
